import { _decorator, Component, Sprite, SpriteFrame, input, Input, KeyCode, EventKeyboard } from 'cc';
import { GroundMap } from './LandMark';  
const { ccclass, property } = _decorator;

@ccclass('MoveRollControl')
export class MoveRollControl extends Component {
    @property([SpriteFrame]) 
    
    cubeFaces: SpriteFrame[] = []; // front, back, left, right, top, bottom

    private faceOrder = [0, 1, 2, 3, 4, 5]; // front, back, left, right, top, bottom

    private sprite: Sprite | null = null;

    @property
    step : number = 300 ; 

    @property(GroundMap) // 地面腳本
    groundMap: GroundMap = null;
    
    
    start() {
       
        this.sprite = this.getComponent(Sprite);

       
        this.updateTopFace();

        
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onKeyDown(event: EventKeyboard) {
        
        switch (event.keyCode) {
            case KeyCode.ARROW_UP:
            case KeyCode.KEY_W:
                this.rollCube("up");
                this.node.position = this.node.position.add3f(0, this.step, 0);
                break;
            case KeyCode.ARROW_DOWN:
            case KeyCode.KEY_S:
                this.rollCube("down");
                this.node.position = this.node.position.add3f(0, -this.step, 0);
                break;
            case KeyCode.ARROW_LEFT:
            case KeyCode.KEY_A:
                this.rollCube("left");
                this.node.position = this.node.position.add3f(-this.step, 0, 0);
                break;
            case KeyCode.ARROW_RIGHT:
            case KeyCode.KEY_D:
                this.rollCube("right");
                this.node.position = this.node.position.add3f(this.step, 0, 0);
                break;
        }

        
        this.updateTopFace();
    }

    rollCube(direction: string) {
        const [front, back, left, right, top, bottom] = this.faceOrder;

        if (direction === "up") {
            
            this.faceOrder = [bottom, top, left, right, front, back];
        } else if (direction === "down") {
            
            this.faceOrder = [top, bottom, left, right, back, front];
        } else if (direction === "right") {
           
            this.faceOrder = [front, back, bottom, top, left, right];
        } else if (direction === "left") {
        
            this.faceOrder = [front, back, top, bottom, right, left];
        }

        this.updateGround();
    }

    updateTopFace() {
        const topFaceIndex = this.faceOrder[5]; 
        if (this.sprite && this.cubeFaces[topFaceIndex]) {
            this.sprite.spriteFrame = this.cubeFaces[topFaceIndex];
        }
    }

    updateGround() {
        const bottomFaceIndex = this.faceOrder[5]; 
        const bottomFaceSprite = this.cubeFaces[bottomFaceIndex];

       
        const gridIndex = 1; 
        if (this.groundMap) {
            this.groundMap.updateGround(bottomFaceSprite, gridIndex); 
        }
    }
    
}
